package com.yd.app.service.common;

import com.yd.app.util.BusinessException;
import com.yd.app.util.HexUtil;
import com.yd.app.util.XOR;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/3/20.
 */
@Service
public class BaseService {
    /**
     *根据分页页码获取数据库开始记录数
     */
    protected int getStartRow(int pageIndex, int pageSize){
        pageIndex=pageIndex<1?1:pageIndex;
        return (pageIndex-1)*pageSize;
    }
    /**
     * 对密码进行加密
     * @author
     * @param str 加密字符串 password
     * @param key 盐   username
     * @return 加密后字符串
     */
    public String passwordEncoding(String str, String key) throws BusinessException {
        //判断是否为40位的字符串
        Pattern pattern = Pattern.compile("[0-9A-Z]{40}");
        Matcher isPassword = pattern.matcher(str);
        if(isPassword.matches())
            return str;
        else
        {
            byte[] encrypt = XOR.encrypt(str.getBytes(), key);
            byte[] sha = {};
            try {
                sha = XOR.CryptUtil.encryptSHA(encrypt);
            } catch (Exception e) {

                throw new BusinessException(500, "加密失败", "encrypt_error");
            }
            return HexUtil.bytesToHex(sha);
        }
    }
    //删除文件
    protected void deleteFile(String url){
        File file = new File(url);
        if(file.exists() && !file.isDirectory()){
            file.delete();
        }
    }

    public String  getToken(String str,String str1){
        String returnStr="";
        List<String> list=new ArrayList<String>();
        list.add(str);list.add(str1);
        Collections.sort(list);
        for(String s: list){
            returnStr =returnStr+s+"_";
        }
        return returnStr.substring(0,returnStr.length()-1);
    }

    public String getStrFromList(List<String> list){
        String str="'";
        for(String s:list){
            str+=s+"','";
        }
        return str.substring(0,str.length()-2);
    }
}
